# -*- coding: utf-8 -*-
from odoo import models, fields, api
from odoo.osv import osv
from datetime import datetime
import time
from odoo.tools.translate import _
from odoo.exceptions import ValidationError,Warning

import logging
_logger = logging.getLogger(__name__)


class EmployeeTraining(models.Model):
    _inherit = 'employee.training'

    tags = fields.Many2many('hr.employee.category', 'train_category_rel', 'train_id', 'category_id', string='Tags')
    address = fields.Char('Address')
    training_id = fields.Many2many('hr.employee', string='Employee Details', compute="employee_details", inverse='_set_employee',readonly=False)
    department_ids = fields.Many2many('hr.department','employee_train_depart_rel','train_id','depart_id', string='Department', required=True)
    exclude_training_id = fields.Many2many('hr.employee', string='exclude employees',readonly=False)
    #exclude_training_id = fields.One2many('hr.employee', string='Except employees', compute="exclude_details", inverse='_set_exclude',readonly=False)
    train_employees = fields.Char('trainees list')
    #exclude_employees = fields.Char('exclude_employee_list')
    scores = fields.One2many('employee.score','the_train',string = 'trainees score')
    information_attachment = fields.Many2many('ir.attachment', compute='_get_attachment_ids', string='attachments')

    def _get_attachment_ids(self):
        att_model = self.env['ir.attachment'] #获取附件模型
        for obj in self:
            query = [('res_model', '=', self._name), ('res_id', '=', obj.id)]   #根据res_model和res_id查询附件
            obj.information_attachment = att_model.search(query) #取得附件list

    
    def _set_employee(self):
        cat_ids = self.env['hr.employee.category'].browse([])
        has_dep = False
        for e in self.training_id:
            if e.department_id.id in self.department_ids.ids:
                has_dep = True
            cat_ids |= e.category_ids
        if not has_dep:
            #pass
            self.department_ids = None
        tag_ids = self.tags
        if (cat_ids & tag_ids)< tag_ids:
            #pass
            self.tags = cat_ids & tag_ids
        
        if self.train_employees:
            list = [int(i) for i in self.train_employees.split(',')]
        else:
            list = []
        exclude_ids= (self.env['hr.employee'].browse(list)-self.training_id).ids
        self.exclude_training_id=[(6,0, exclude_ids) ]

    @api.onchange('department_ids','tags')
    def employee_details(self):
        list = []
        emps= self.env['hr.employee'].search([])
        #res = emps
        #res1 = emps
        if self.department_ids:
            res= emps.filtered(lambda r: r.department_id.id in self.department_ids.ids)
            #res= emps.filtered(lambda r: r.department_id.id in self.department_ids.ids)
        else:
            res= emps.browse([])
        if self.tags:
            for e in emps:
                match = any(map(lambda v: v in e.category_ids.ids, self.tags.ids))
                if match :
                    list.append(e.id)
            res1 = emps.browse(list)
        else:
            res1 = emps.browse([])
        '''  
        self.tmp_employee_list = res|res1
        self.update({'training_id': self.tmp_employee_list})
        
        strlist=','.join([str(i) for i in self.tmp_employee_list.ids])
        self.train_employees = strlist
        '''
        self.tmp_employee_list = res|res1
        if self.exclude_training_id:
            self.tmp_employee_list -= self.exclude_training_id
        self.training_id = self.tmp_employee_list
        
        strlist=','.join([str(i) for i in self.tmp_employee_list.ids])
        self.train_employees = strlist
        '''
        strlist1=','.join([str(i) for i in self.exclude_training_id.ids])
        self.exclude_employees = strlist1
        '''
        
    def _set_exclude(self):
        pass
    
    def exclude_details(self):
         pass
    
    
    
    def score_event(self):
        res = self.env['employee.score'].search([('the_train', '=', self.id)]).mapped(lambda r: r.emp)
        tmp_emp = self.training_id - res
        if tmp_emp:
            for value in tmp_emp:
                self.env['employee.score'].create({
                    'emp': value.id,
                    'the_train':self.id,
                    'scorer':self.env.user.id,
                })
        res1 = res - self.training_id
        if res1:
            res2 = self.env['employee.score'].search([('emp', 'in', res1.ids)])
            res2.unlink()


    
    def write(self,values):
        result = super(EmployeeTraining,self).write(values)
        partners=[]
        excludes=[]
        if self.training_id:
            partners = [i.user_id.partner_id.id  for i in self.training_id  if i.user_id.partner_id ]
            partners.extend([i.id for i in self.message_follower_ids.mapped('partner_id')])
        if partners:
            self.message_subscribe(partner_ids=partners)
        if self.exclude_training_id:
            excludes = [i.user_id.partner_id.id  for i in self.exclude_training_id  if i.user_id.partner_id ]
        if excludes:
            self.message_unsubscribe(partner_ids=excludes)
        return result
# ===============>>>>>>>>================<<<<<<<<<<<==============

# class PartnerTrainer(models.Model):
#     _name = 'partner.trainer'
#     _inherit = ['mail.thread']
#     _rec_name = 'partner_name'
#
#     partner_name = fields.Many2one(comodel_name='res.partner', track_visibility='onchange', string='Trainer',required=True)
#     image_id = fields.Binary('Image', related='partner_name.image')

class ChecklistLine(models.Model):
    _inherit = 'checklist.line'
    note_id = fields.Text('Description')
